const { User, Role, Menu, getUserRole } = require("../models/role");
// 权限控制中间件

async function checkRole(req, res, next, role) {
  let id = req.userId;
  if (!id) {
    res.json({
      code: 400,
      message: "无权限",
      data: null,
    });
    return;
  }
  // 查询用户所含有的角色以及对应菜单的关系
  let roles = await getUserRole(id);
  for (let i = 0; i < roles.length; i++) {
    if (roles[i].menu_code === role) {
      next();
      return;
    }
  }

  res.json({
    code: 400,
    message: "无权限",
    data: null,
  });
  return;
}

module.exports = {
  checkRole,
};
